package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    /**
     * 登录方法
     *
     * @param dto 前端小程序传过来的临时登录凭证
     * @return
     */
    @Override
    @Transactional
    public Result<UserLoginVO> login(UserLoginDTO dto) {
        //1.非空判断
        if(dto.getCode()==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //2.远程调用微信官方接口auth.code2Session
        String url="https://api.weixin.qq.com/sns/jscode2session";
        //2.1 封装请求参数
        Map<String, String> paramMap=new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",dto.getCode());
        paramMap.put("grant_type","authorization_code");
        //2.2发起get请求，并获取响应对象
        String body = HttpClientUtil.doGet(url, paramMap);
        //2.3 转对象map
        Map map = JSONObject.parseObject(body, Map.class);
        if(map==null || map.size()==0){
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
        //2.4获取登录之后的唯一标识openId
        String openid = (String) map.get("openid");

        //3.根据openid去查询user表，如果没有数据，则进行注册
            //3.1 查询user表
        User user = userMapper.getUserByOpenId(openid);
            //3.2 如果没有数据，则进行注册
        if(user==null){
             user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
        }
        //4.封装数据返回
        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())//用户id
                .openid(openid)
                .token(JwtUtil.getToken(user.getId()))
                .build();

        return Result.success(vo);
    }
}
